package org.ww.ware.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.constant.RabbitMqConstant;
import org.ww.common.to.mq.OrderTo;
import org.ww.common.to.mq.StockLockedTo;
import org.ww.ware.service.WareSkuService;

import java.io.IOException;

/**
 * @program: gmall
 * @description:
 * @author: ww
 * @create: 2024-10-31 13:36
 **/
@Slf4j
@Service
@RabbitListener(queues = RabbitMqConstant.STOCK_RELEASE_STOCK_QUEUE)
public class StockLockListener {
    @Autowired
    private WareSkuService wareSkuService;
    /**
     * 锁库存成功，但是后续业务出错，需要库存自动解锁
     * @param message
     * @param channel
     * @param to
     */
    @RabbitHandler
    public void handlerStockLockMessage(Message message, Channel channel, StockLockedTo to) throws IOException {
        log.info("收到库存解锁信息：【{}】",to);
        try {
            wareSkuService.stockUnLock(to);
            //第二个参数是否批量确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //第二个参数是否重回队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handlerOrderReleaseMessage(Message message, Channel channel, OrderTo to) throws IOException {
        log.info("收到订单取消--库存解锁信息：【{}】",to);
        try {
            wareSkuService.unLockStock(to);
            //第二个参数是否批量确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //第二个参数是否重回队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
